import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'  // 根路径重定向到登录页
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { 
      title: '登录',
      noAuth: true  // 标记不需要认证的页面
    }
  },
  {
    path: '/main',
    component: () => import('@/layout/index.vue'),
    redirect: '/main/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'department',
        name: 'Department',
        component: () => import('@/views/DepartmentManagement.vue'),
        meta: { title: '部门管理' }
      },
      {
        path: 'employee',
        name: 'Employee',
        component: () => import('@/views/EmployeeManagement.vue'),
        meta: { title: '员工管理' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 智学云帆教学管理系统` : '智学云帆教学管理系统'
  
  // 不需要认证的页面直接放行
  if (to.meta.noAuth) {
    if (token && to.path === '/login') {
      next('/main/dashboard')  // 已登录时访问登录页，重定向到首页
    } else {
      next()
    }
    return
  }
  
  // 需要认证但没有token的情况
  if (!token) {
    next('/login')
    return
  }
  
  next()
})

export default router 